import { useState, useEffect } from "react";

const Countdown = () => {
  const [seconds, setSeconds] = useState(60);
  const [isFinished, setIsFinished] = useState(false);
  useEffect(() => {
    console.log("useEffect 执行了，当前 seconds:", seconds); // 只会打印一次: "useEffect 执行了，当前 seconds: 60"

    let timer = setInterval(() => {
      console.log("定时器执行，闭包中的 seconds:", seconds); // 永远打印: "定时器执行，闭包中的 seconds: 60"

      if (seconds === 0) {
        console.log("应该停止了！"); // 这行永远不会执行
        setSeconds(0);
        return clearInterval(timer);
      }
      setSeconds((prev) => {
        console.log("设置新值:", prev - 1); // 这个会正常执行: 59, 58, 57, ..., 0, -1, -2, ...
        return prev - 1;
      });
    }, 1000);

    return () => {
      console.log("清理定时器");
      clearInterval(timer);
    };
  }, [isFinished]);
  const handleReset = () => {
    setSeconds(60);
    setIsFinished(false);
  };

  return (
    <div className="countdown-container">
      <div className="countdown-display">
        <h1>{seconds > 0 && <h2>倒计时: {seconds} 秒</h2>}</h1>
      </div>

      {seconds === 0 && (
        <div className="finished-message">
          <p>时间到了！</p>
        </div>
      )}

      <div className="reset-button-container">
        <button onClick={handleReset} className="reset-button">
          重置
        </button>
      </div>
    </div>
  );
};
export default Countdown;
